var express = require('express');
var router = express.Router();
let multiparty = require('multiparty')
let xlsx = require('node-xlsx')
let fs = require('fs')
var {
  academyModel,
  stageModel,
  questionModel,
  paperModel,
  adminModel,
  studentModel,
  clazzModel,
  treeModel
} = require("../model/model");
const { set } = require('mongoose');
//导入
router.post('/upload', (req, res) => {
  let form = new multiparty.Form()
  form.uploadDir = 'upload'
  form.parse(req, (error, formData, ImageData) => {
    let path = ImageData.file[0].path
    let [{ data }] = xlsx.parse(path)
    data.shift()
    data.forEach(async (item) => {
      let obj = {
        name: item[0],
        role: item[1],
        email: item[2],
        phone: item[3],
        truename: item[4],
        academy: item[5]
      }
      await adminModel.create(obj)
    })
  })
  res.send({
    code: 200
  })
})
//导出
router.get('/exportFile', async (req, res) => {
  const data = await adminModel.find().populate('academy')
  const ress = data.map(item => {
    return [
      item.truename,
      item.name,
      item.academy.name,
      item.role,
      item.email,
      item.phone,
      item.status,
    ]
  })
  const xlsxData = [
    ['姓名', '用户名', '学院', '角色名称', '电话', '邮箱', '是否启用'],
    ...ress
  ]
  const buffer = xlsx.build([{ name: 'admin.xlsx', data: xlsxData }])
  fs.writeFile('user.xlsx', buffer, (err) => {
    if (err) {
      console.log('写入失败');
    } else {
      console.log('写入成功');
    }
  })
  res.send({
    code: 200
  })
})
//获取管理员表
router.get('/adminList', async (req, res) => {
  let data = await adminModel.find().populate('academy')
  console.log(data,'222222222222222222');
  res.send({
    code: 200,
    data: data
  })
})
//搜索
router.post('/adminList1', async (req, res) => {
  // console.log(req.body);
  
  let { searchName, searchAcademy, searchRole } = req.body
  let name = RegExp(searchName)
  let arr = [{}]
  if (name) {
    arr.push({ truename: name })
  }
  if (searchAcademy) {
    arr.push({ academy: searchAcademy })
  }
  if (searchRole) {
    arr.push({ role: searchRole })
  }
  let data = await adminModel.find({ $and: arr }).populate('academy')
  // console.log(data);
  
  res.send({
    code: 200,
    data: data
  })
})
//获取学院表  academy
router.get('/academyList', async (req, res) => {
  let data = await academyModel.find()
  res.send({
    code: 200,
    data: data
  })
})
//是否启用
router.post('/changeStatus', async (req, res) => {
  let { status, id } = req.body
  await adminModel.findByIdAndUpdate(id, { status: status }, { new: true })
  res.send({
    code: 200
  })
})
//修改admin表
router.post('/updateAdmin', async (req, res) => {
  console.log(req.body, 11111111111111111111111);
  let { adminId, updateName, updatePhone, updateAcademy, updateRole } = req.body
  let data = await adminModel.findOne({ _id: adminId })
  let copy = data
  copy.truename = updateName,
    copy.phone = updatePhone,
    copy.academy = updateAcademy,
    copy.role = updateRole
  await adminModel.updateOne({ _id: adminId }, copy)
  res.send({
    code: 200
  })
})
//学生列表
router.get('/studentList', async (req, res) => {
  let data = await studentModel.find().populate('clazz')
  console.log(data, '111111111111111111111111111111111');

  res.send({
    code: 200,
    data: data
  })
})
router.post('/studentList1', async (req, res) => {
  console.log(req.body);
  let { name, xh, sex, aid } = req.body
  let n = RegExp(name)
  let arr = [{}]
  if (name) {
    arr.push({ name: n })
  }
  if (xh) {
    arr.push({ tid: xh })
  }
  if (sex == '1') {
    arr.push({ sex: true })
  }
  if (sex == '2') {
    arr.push({ sex: false })
  }
  let data = await studentModel.find({ $and: arr }).populate('clazz')
  // console.log(data);
  
  if (aid!='') {
    try {
      let ls = await academyModel.find({ _id: aid });
      let jieduan = await stageModel.find({ _id: aid })
      if (ls.length > 0) {
        let lss = await stageModel.find({ academy: aid });
        let stagemap = lss.map(item => item._id)
        let clist = await clazzModel.find({ stage: { $in: stagemap } })
        let clazzmap = clist.map(item => item._id)
        data = await studentModel.find({ clazz: { $in: clazzmap } }).populate('clazz')
      }
      if (jieduan.length > 0) {
        let stagemap = jieduan.map(item => item._id)
        let clist = await clazzModel.find({ stage: { $in: stagemap } })
        let clazzmap = clist.map(item => item._id)
        data = await studentModel.find({ clazz: { $in: clazzmap } }).populate('clazz')
      } else {
        data = await studentModel.find({ clazz: aid }).populate('clazz')
      }
      res.send({
        code: 200,
        data: data // 返回符合条件的学生数据
      });
    } catch (err) {
      console.error('Error occurred:', err); // 记录错误
      res.send({
        code: 500,
        data: []
      })
    }
  } else {
    res.send({
      code: 500,
      data: data
    })
  }
})
//删除学生
router.post('/studel', async (req, res) => {
  let id = req.body.id
  await studentModel.deleteOne({ _id: id })
  res.send({
    code: 200
  })
})
//班级表
router.get('/clazzList', async (req, res) => {
  let data = await clazzModel.find().populate('stage')
  res.send({
    code: 200,
    data: data
  })
})
router.get('/stage', async (req, res) => {
  try {
    await treeModel.deleteMany({}); // 清空 treeModel 数据
    // 获取所有相关数据
    const [data, ls, lss] = await Promise.all([
      stageModel.find().populate('academy').populate('class'),
      academyModel.find(),
      clazzModel.find()
    ]);
    // 创建要插入 treeModel 的数据
    const treeData = [];
    // 添加学院数据
    ls.forEach(item => {
      treeData.push({ name: item.name, aid: item._id });
    });
    // 添加阶段数据
    data.forEach(item => {
      treeData.push({
        name: item.name,
        sid: item.academy,
        aid: item._id
      });
    });
    // 添加班级数据
    lss.forEach(item => {
      treeData.push({
        name: item.name,
        sid: item.stage,
        aid: item._id
      });
    });
    // 批量插入所有数据
    await treeModel.insertMany(treeData);
    // 构建树形结构
    const info = await treeModel.find().lean();
    const obj = {};
    const arr1 = [];
    // 构建对象并整理树形结构
    info.forEach(item => {
      obj[item.aid] = item;
      if (item.sid) {
        if (obj[item.sid]&&!obj[item.sid].children) {
          obj[item.sid].children = [item];
        } else {
          obj[item.sid]?.children.push(item);
        }
      } else {
        arr1.push(item);
      }
    });
    res.send({
      code: 200,
      data: arr1
    });
  } catch (err) {
    console.error('Error occurred:', err); // 记录错误
    res.status(500).send({ code: 500, message: 'Internal Server Error' });
  }
});
//修改studen数据
router.post('/upDateStudent', async (req, res) => {
  // console.log(req.body);
  let id = req.body.id
  let obj = req.body
  delete obj.id
  if (obj.sex === 1) {
    obj.sex = true
  } else if (obj.sex === 2) {
    obj.sex = false
  }
  await studentModel.updateOne({ _id: id }, obj)
  res.send({
    code: 200
  })
})
//学生表批量导出
router.get('/exportStudent', async (req, res) => {
  const data = await studentModel.find().populate('clazz')
  const ress = data.map(item => {
    return [
      item.name,
      item.tid,
      item.sex ? '男' : '女',
      item.address,
      item.ice,
      item.phone,
      item.clazz.name,
    ]
  })
  const xlsxData = [
    ['学生名称', '学号', '性别', '家庭住址', '紧急联系人', '紧急联系人电话', '班级'],
    ...ress
  ]
  const buffer = xlsx.build([{ name: 'admin.xlsx', data: xlsxData }])
  fs.writeFile('student.xlsx', buffer, (err) => {
    if (err) {
      console.log('写入失败');
    } else {
      console.log('写入成功');
    }
  })
  res.send({
    code: 200
  })
})
//student批量导入
router.post('/upload1', async (req, res) => {
  let ls = await clazzModel.find()
  let form = new multiparty.Form()
  form.uploadDir = 'upload'
  form.parse(req, (error, formData, ImageData) => {
    let path = ImageData.file[0].path
    let [{ data }] = xlsx.parse(path)
    data.shift()
    data.forEach(async (item) => {
      let obj = {
        name: item[0],
        tid: item[1],
        sex: item[2] == '男' ? true : false,
        address: item[3],
        ice: item[4],
        phone: item[5],
        clazz: ls.filter(ele => ele.name === item[6])[0]._id,
        img:item[7]
      } 
      await studentModel.create(obj)
    })
  })
  res.send({
    code: 200
  })
})
router.post('/addStudent', async (req, res) => {
  await studentModel.create(req.body)
  res.send({
    code: 200
  })
})
router.post('/delTree', async (req, res) => {
  let { id } = req.body
  let ls = await academyModel.find({ _id: id })
  if (ls.length > 0) {
    await academyModel.deleteOne({ _id: req.body.id })
    let lss = await stageModel.find({ academy: id })
    let l = lss.map(item => item._id)
    await stageModel.deleteOne({ academy: req.body.id })
    await clazzModel.deleteMany({ stage: { $in: l } })
  }
  let ts = await stageModel.find({ _id: id })
  if (ts.length > 0) {
    let l = ts.map(item => item._id)
    await stageModel.deleteOne({ _id: req.body.id })
    await clazzModel.deleteMany({ stage: { $in: l } })
  }
  let ss = await clazzModel.find({ _id: id })
  if (ss.length > 0) {
    await clazzModel.deleteOne({ _id: req.body.id })
  }
  res.send({
    code: 200
  })
})
router.post('/addTree', async (req, res) => {
  let { id, name,creator } = req.body
  let data = await academyModel.find({ _id: req.body.id })
  let data1 = await stageModel.find({ _id: req.body.id })
  if (data.length > 0) {
    let obj = {
      academy: id,
      name: name,
      creator
    }
    await stageModel.create(obj)
    res.send({
      code: 200,
    })
  }
  if (data1.length > 0) {
    let obj = {
      name: name,
      stage: id
    }
    let lss = await clazzModel.create(obj)
    let index = lss._id
    let obj1 = data1[0]
    obj1['class'] = index
    await stageModel.updateOne({ _id: id }, obj1)
    res.send({
      code: 200,

    })
  }
})
router.post('/addXueyuan', async (req, res) => {
  await academyModel.create(req.body)
  res.send({
    code: 200
  })
})
module.exports = router;